package com.wyl.controller;

import cn.hutool.core.date.DateTime;
import com.wyl.dto.SendDelayMsgDto;
import com.wyl.dto.SendTtlMsgDto;
import com.wyl.mq.config.DelayQueueConfig;
import com.wyl.mq.config.TtlQueueConfig;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageProperties;
import org.springframework.amqp.core.MessagePropertiesBuilder;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.nio.charset.StandardCharsets;

/**
 * @author 吴宇亮 on 2023/6/9 13:45
 */
@RestController
@RequestMapping("/ttl")
public class TtlQueueController {

    @Resource
    private RabbitTemplate rabbitTemplate;

    @PostMapping("/sendTtlMsg")
    public String sendTtlMsg(@RequestBody SendTtlMsgDto dto) {
        MessageProperties messageProperties = MessagePropertiesBuilder.fromProperties(new MessageProperties()).setExpiration(dto.getTtl()).build();
        String msg = dto.getMsg();
        msg = msg + "(发送时间: " + DateTime.now().toTimeStr() + "，延迟时间: " + dto.getTtl() + " )";
        Message message = new Message(msg.getBytes(StandardCharsets.UTF_8), messageProperties);
        rabbitTemplate.send(TtlQueueConfig.ttlQueueInput, message);
        return "成功发送消息：" + dto.getMsg();
    }

    @PostMapping("/sendDelayMsg")
    public String sendDelayMsg(@RequestBody SendDelayMsgDto dto) {
        MessageProperties messageProperties = new MessageProperties();
        messageProperties.setDelay(dto.getDelay());
        String msg = dto.getMsg();
        msg = msg + "(发送时间: " + DateTime.now().toTimeStr() + "，延迟时间: " + dto.getDelay() + " )";
        Message message = new Message(msg.getBytes(StandardCharsets.UTF_8), messageProperties);
        rabbitTemplate.send(DelayQueueConfig.delayExchange, "-", message);
        return "成功发送消息：" + dto.getMsg();
    }

}
